package multi_thread.master.tools;

import java.util.concurrent.*;

/**
 * @author Cheng Jun
 * Description:
 * CyclicBarrier /ˈsaɪklɪk/ /ˈbæriə(r)/ 是在所有的参赛选手（所有线程）都到了栅栏时，同时继续往下执行；
 * @version 1.0
 * @date 2020/3/6 17:38
 * @see CyclicBarrier
 * @see CountDownLatchExample
 */
public class CyclicBarrierExample {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService executor = Executors.newFixedThreadPool(3);
        executor.submit(new Runner(cyclicBarrier, "一号种子选手"));
        executor.submit(new Runner(cyclicBarrier, "二号种子选手"));
        executor.submit(new Runner(cyclicBarrier, "三号种子选手"));
        executor.shutdown();
    }

    static class Runner implements Runnable {

        private CyclicBarrier cyclicBarrier;

        private String name;

        public Runner(CyclicBarrier cyclicBarrier, String name) {
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }

        @Override
        public void run() {
            try {
                System.out.println(name + " ready go!");
                // 看 java.util.concurrent.CyclicBarrier.await() 源码注释
                cyclicBarrier.await();
                System.out.println(name + "go1");
                cyclicBarrier.await();
                System.out.println(name + "go2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

}
